#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:courseService.py
# author:jackiex
# datetime:2022/2/16 13:38
# software: PyCharm

'''
    添加课程服务类，实现相应的方法
'''
from ..models import db
from ..models.courseModel import Course
from ..utils.response_code import RET, error_map_EN


class CourseService(Course):

    @classmethod
    def sub_count(cls, courseID):
        """
         判断可选人数，并实现选课可选人数减一功能
        :param courseID:课程编号
        """
        # 设定好查询参数-根据课程ID查询
        param_list = [Course.isDelete == 0, Course.courseID == courseID]
        try:
            db.session.commit()  # 先行commit一次，解决可能数据滞后的问题
            res_course = db.session.query(Course).filter(*param_list).with_for_update().first()
            if res_course.count > 0:  # 判断此时可选人数是否还有剩余
                res_course.count -= 1
                db.session.commit()
            else:
                return {'code': RET.DATAERR, 'message': error_map_EN[RET.DATAERR], 'data': res_course.count}
        except Exception as e:
            db.session.rollback()
            print("sub_count: ======={}=======".format(e))
        finally:
            if not db.session:
                db.session.close()
